package com.mx.tool.form.window.other;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mx.tool.util.NotifyUtil;
import com.mx.tool.result.IpResult;
import com.mx.tool.result.R;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 徐建鹏.
 * @create: 2021-11-10 19:19
 * @Description:
 */
public class IpWindow {

    private JPanel jPanel;
    private JTextArea textArea;
    private JTextField textField;
    private JButton queryButton;
    private JButton localButton;
    private final Gson gson = new GsonBuilder().setPrettyPrinting().create();

    public JPanel getContent() {
        return jPanel;
    }

    public IpWindow() {
        queryButton.addActionListener(e -> {
            String ip = textField.getText();
            if (StringUtils.isBlank(ip)) {
                NotifyUtil.error("请输入ip地址");
                return;
            }
            R result = getIpInfo(ip);
            textArea.setText(gson.toJson(result));
        });
        localButton.addActionListener(e -> {
            R result = getIpInfo(null);
            textArea.setText(gson.toJson(result));
        });
    }

    public R getIpInfo(String ip) {
        Map<String, Object> param = new HashMap<>();
        param.put("json", true);
        param.put("ip", ip);
        String resultStr = HttpUtil.post("http://whois.pconline.com.cn/ipJson.jsp", param);
        if (StringUtils.isBlank(resultStr)) {
            return R.craate().code("-50").msg("ip查询失败");
        }
        IpResult ipResult = JSON.parseObject(resultStr, IpResult.class);
        if (ipResult == null) {
            return R.craate().code("-50").msg("ip查询失败");
        }
        return R.craate().code("0").msg("查询成功").data(ipResult);
    }

}
